package com.shinhye.mobilelottery.engine.impl;

import java.io.StringReader;

import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

import com.shinhye.mobilelottery.ConstantValue;
import com.shinhye.mobilelottery.bean.ShoppingCart;
import com.shinhye.mobilelottery.bean.Ticket;
import com.shinhye.mobilelottery.bean.User;
import com.shinhye.mobilelottery.engine.BaseEngine;
import com.shinhye.mobilelottery.engine.UserEngine;
import com.shinhye.mobilelottery.net.protocol.Message;
import com.shinhye.mobilelottery.net.protocol.element.BalanceElement;
import com.shinhye.mobilelottery.net.protocol.element.BetElement;
import com.shinhye.mobilelottery.net.protocol.element.UserLoginElement;
import com.shinhye.mobilelottery.utils.DES;

public class UserEngineImpl extends BaseEngine implements UserEngine {

	@Override
	public Message login(User user) {
		// 步骤一：生成用户登录用xml文件
		// 1、创建UserLoginElement extends Element，并处理其中的两个方法
		// 2、为登录的请求设置数据（密码）
		// 3、创建Message，需要给Header设置username
		// 4、调用message.getxml(UserLoginElement)
		UserLoginElement element = new UserLoginElement();
		element.getActpassword().setValue(user.getPassword());
		Message message = new Message();
		message.getHeader().getUsername().setValue(user.getUsername());
		String xml = message.getXml(element);
		
		// 步骤二：发送xml文件到服务器端
		// 步骤三：回复数据处理——校验数据
		Message res = getResult(xml);
		
		if(res != null) {
			// 步骤四：body里面的信息处理
			// oelement中数据处理
			// 结果返回给调用者
			DES des = new DES();
			String wholebody = "<body>" + des.authcode(res.getBody().getBodyInfo(), "ENCODE", ConstantValue.DES_KEY) + "</body>";
			try {
				//oelement中数据处理
				handleOElement(res, wholebody);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return res;
		}
		return null;
	}

	@Override
	public Message balance(User user) {
		BalanceElement element = new BalanceElement();
		Message message = new Message();
		message.getHeader().getUsername().setValue(user.getUsername());
		String xml = message.getXml(element);
		Message res = getResult(xml);
		if(res != null) {
			DES des = new DES();
			String wholebody = "<body>" + des.authcode(res.getBody().getBodyInfo(), "ENCODE", ConstantValue.DES_KEY) + "</body>";
			try {
				handleOElement(res, wholebody);
				
				BalanceElement balanceEle = new BalanceElement();
				res.getBody().getElements().add(balanceEle);
				
				XmlPullParser parser = Xml.newPullParser();
				StringReader reader = new StringReader(wholebody);
				parser.setInput(reader);
				int type = parser.getEventType();
				while(type != XmlPullParser.END_DOCUMENT) {
					switch(type) {
					case XmlPullParser.START_TAG:
						if("investvalues".equals(parser.getName())) {
							balanceEle.setInvestvalues(parser.nextText());
						}
						break;
					}
					type = parser.next();
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return res;
		}
		return null;
	}

	@Override
	public Message bet(User user) {
		ShoppingCart cart = ShoppingCart.getInstance();
		BetElement element = new BetElement();
		element.getLotteryid().setValue(cart.getLotteryid() + "");
		StringBuffer sb = new StringBuffer();
		for(Ticket ticket : ShoppingCart.getInstance().getTicketBag()) {
			sb.append("^");
			sb.append(ticket.getRedNum().replaceAll(" ", ""));
			sb.append("|");
			sb.append(ticket.getBlueNum().replaceAll(" ", ""));
		}
		element.getLotteryid().setValue(cart.getLotteryid() + "");
		element.getIssue().setValue(cart.getIssue());
		element.getLotterycode().setValue(sb.toString());
		element.getLotterynumber().setValue(cart.getLotterynumber() + "");
		element.getLotteryvalue().setValue(cart.getLotteryvalue() + "");
		element.getAppnumbers().setValue(cart.getAppnumbers() + "");
		element.getIssuesnumbers().setValue(cart.getIssuesnumbers() + "");
		element.getIssueflag().setValue(cart.getIssuesnumbers() > 1 ? "1" : "0");
		
		Message message = new Message();
		message.getHeader().getUsername().setValue(user.getUsername());
		String xml = message.getXml(element);
		Message res = getResult(xml);
		if(res != null) {
			DES des = new DES();
			String wholebody = "<body>" + des.authcode(res.getBody().getBodyInfo(), "ENCODE", ConstantValue.DES_KEY) + "</body>";
			try {
				handleOElement(res, wholebody);
				
				BetElement betEle = new BetElement();
				res.getBody().getElements().add(betEle);
				
				XmlPullParser parser = Xml.newPullParser();
				StringReader reader = new StringReader(wholebody);
				parser.setInput(reader);
				int type = parser.getEventType();
				while(type != XmlPullParser.END_DOCUMENT) {
					switch(type) {
					case XmlPullParser.START_TAG:
						if("actvalue".equals(parser.getName())) {
							betEle.setActvalue(parser.nextText());
						}
						break;
					}
					type = parser.next();
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return res;
		}
		return null;
	}

}
